﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Exceptions;

namespace DDD.Extensions
{
    public static class SerilogExtension
    {
        public static IHostBuilder AddSerilog(this IHostBuilder builder, IConfiguration configuration)
        {
            builder.UseSerilog();
            SerlogConfiguration.Init(configuration);

            return builder;
        }

        public static WebApplication UseSerilogRequestLog(this WebApplication app)
        {
            app.UseSerilogRequestLogging();

            return app;
        }

        private class SerlogConfiguration
        {

            public static void Init(IConfiguration configuration)
            {
                Log.Logger = new LoggerConfiguration()
                   .Enrich.FromLogContext()
                   .Enrich.WithExceptionDetails()
                   .Enrich.WithMachineName()
                   .Enrich.WithEnvironmentUserName()
                   .Enrich.WithThreadId()
                   .Enrich.WithThreadName()
                   .Enrich.WithProcessId()
                   .Enrich.WithProcessName()
                   .Enrich.WithEnvironmentName()
                   .WriteTo.Debug()
                   .WriteTo.Console()
                   .WriteTo.File($"logs/{DateTime.Now.Year}/{DateTime.Now.Month}/.log", rollingInterval: RollingInterval.Day)
                   //.WriteTo.Elasticsearch(CreateElasticsearchSinkOptions(builder.Configuration))
                   .ReadFrom.Configuration(configuration)
                   .CreateLogger();
            }
        }

        //private static ElasticsearchSinkOptions CreateElasticsearchSinkOptions(IConfiguration configuration)
        //{
        //    return new ElasticsearchSinkOptions(new Uri(configuration[AppsettingsConst.ES_URL]))
        //    {
        //        AutoRegisterTemplate = true,
        //        IndexFormat = configuration[AppsettingsConst.ES_INDEX_FORMAT],
        //        NumberOfReplicas = 2,
        //        NumberOfShards = 1,
        //        OverwriteTemplate = true,
        //        TypeName = null,
        //        EmitEventFailure = EmitEventFailureHandling.RaiseCallback,
        //        AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
        //        FailureCallback = e =>
        //        {
        //            Console.WriteLine("es日志写入异常！！！！！！！！！！！！！");
        //        },
        //        //MinimumLogEventLevel = LogEventLevel.Verbose,
        //        BatchAction = ElasticOpType.Create,
        //        BatchPostingLimit = 50,
        //        //ModifyConnectionSettings = connectionConfiguration =>
        //        //{
        //        //    //connectionConfiguration.OnRequestCompleted(apiCallDetail =>
        //        //    //{
        //        //    //    string logEventStr = Encoding.UTF8.GetString(apiCallDetail.RequestBodyInBytes);
        //        //    //    var logEvent = JsonConvert.DeserializeObject<LogEvent>(logEventStr);
        //        //    //    logEvent.AddPropertyIfAbsent(new LogEventProperty("Id", new ScalarValue(Guid.NewGuid())));
        //        //    //    apiCallDetail.RequestBodyInBytes = LogEvent.ToBytes(logEvent);
        //        //    //});
        //        //    connectionConfiguration.OnRequestDataCreated(requestData =>
        //        //    {
        //        //        if (requestData.PostData != null)
        //        //        {
        //        //            var idData = new { id = Guid.NewGuid().ToString() };
        //        //            var jsonString = JsonConvert.SerializeObject(idData);
        //        //            byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
        //        //            using MemoryStream memoryStream = new MemoryStream(bytes);
        //        //            requestData.PostData.Write(memoryStream, connectionConfiguration);
        //        //        }
        //        //    });
        //        //    return connectionConfiguration;
        //        //}
        //    };
        //}
    }
}
